package cn.gailvlun.gll.presentation.profile;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ObservableBoolean;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import org.joda.time.DateTime;
import org.joda.time.Period;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.chatlib.db.ChatDB2;
import cn.gailvlun.gll.databinding.ActivityOtherProfileBinding;
import cn.gailvlun.gll.databinding.PopupOperations1Binding;
import cn.gailvlun.gll.net.GsonUtil;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.base.IsFriendRes;
import cn.gailvlun.gll.net.base.Profile;
import cn.gailvlun.gll.net.base.friend.AddFriendReq;
import cn.gailvlun.gll.net.base.friend.FriendNotification;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.chat.ChatActivity;
import cn.gailvlun.gll.util.DateUtil;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.ReportUtil;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.SPUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.realm.Realm;



public class OtherProfileActivity extends BaseActivity {

    public static void openActivity(Context context, Profile profile) {
        Intent intent = new Intent(context, OtherProfileActivity.class);
        intent.putExtra("profile", GsonUtil.getGson().toJson(profile));
        context.startActivity(intent);
    }

    public static void openActivityByChat(Context context, Profile profile) {
        Intent intent = new Intent(context, OtherProfileActivity.class);
        intent.putExtra("profile", GsonUtil.getGson().toJson(profile));
        intent.putExtra("from", "chat");
        context.startActivity(intent);
    }

    public static void openActivity(Context context, Profile profile, boolean isFriend) {
        Intent intent = new Intent(context, OtherProfileActivity.class);
        intent.putExtra("profile", GsonUtil.getGson().toJson(profile));

        context.startActivity(intent);
    }

    private ActivityOtherProfileBinding mBinding;
    private Profile mProfile;
    private boolean isFriend;
    LayoutInflater layoutInflater;
    PopupWindow popupWindow;
    ViewGroup contentView;
    private ObservableBoolean isBlack = new ObservableBoolean(false);

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_other_profile);
        mBinding.setPresenter(new Presenter());
        layoutInflater = LayoutInflater.from(mContext);
        PopupOperations1Binding popupBinding = DataBindingUtil.inflate(layoutInflater, R.layout.popup_operations1, null, false);
        popupBinding.setIsBlack(isBlack);
        popupWindow = new PopupWindow(
                popupBinding.getRoot(),
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setOutsideTouchable(true);
        contentView = findViewById(android.R.id.content);
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.nbv.setOnMenuClickListener(new NavigationBarView.OnMenuClickListener() {
            @Override
            public void onMenuClick(NavigationBarView nb) {
                popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);

            }
        });
        popupWindow.setAnimationStyle(R.style.BaseDialog_Bottom_UP);
        popupWindow.getContentView().findViewById(R.id.tv_report).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    new ReportUtil(mContext).show();
                }

            }
        });
        popupWindow.getContentView().findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });

        popupWindow.getContentView().findViewById(R.id.tv_add_black_list).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    new MaterialDialog.Builder(mContext)
                            .title("加入黑名单")
                            .content("加入黑名单，你将不再收到对方的消息(包括好友申请通知)")
                            .positiveText("确定")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                    
                                    ToastUtil.showShort("该用户已经被拉黑，无法发送好友申请");
                                    SPUtil.put(SPUtil.USER, "pre_is_black-"+mProfile.getId(), true);
                                    isBlack.set(true);

                                }
                            })
                            .negativeText("取消")
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                }
                            })
                            .show();
                }
            }
        });

        popupWindow.getContentView().findViewById(R.id.tv_remove_black_list).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    isBlack.set(false);
                    SPUtil.put(SPUtil.USER, "pre_is_black-"+mProfile.getId(), false);

                }
            }
        });

    }

    private String from;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        Intent intent = getIntent();
        String profile = intent.getStringExtra("profile");
        from = intent.getStringExtra("from");

        mProfile = GsonUtil.getGson().fromJson(profile, Profile.class);
        mBinding.setItem(mProfile);
        isBlack.set(SPUtil.getBoolean(SPUtil.USER, "pre_is_black-"+mProfile.getId()));
        mBinding.setIsBlack(isBlack);

        final Dialog dialog = DialogUtil.showIndeterminate(mContext);
        HttpMethods.getBaseService()
                .isFriend(mProfile.getId())
                .compose(RxUtil.<IsFriendRes>applyScheduler())
                .compose(this.<IsFriendRes>bindToLifecycle())
                .subscribe(new HttpSubscriber<IsFriendRes>() {
                    @Override
                    protected void onSuccess(IsFriendRes response) {
                        isFriend = response.isIs_friend();
                        mBinding.setIsFriend(isFriend);

                        if (from != null) {
                            if (!isFriend && "chat".equals(from)) {
                                mBinding.tvTempChat.setVisibility(View.VISIBLE);
                            }
                        }
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable IsFriendRes response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        dialog.dismiss();
                    }
                });
    }

    public class Presenter {
        public void onClickBottom(Profile item, Boolean isFriend) {
            if (isFriend) {
                Realm realm = Realm.getInstance(ChatDB2.INSTANCE.getConfiguration());
                realm.beginTransaction();
                realm.insertOrUpdate(item);
                realm.commitTransaction();
                realm.close();

                ChatActivity.openActivity(mContext, "user:" + item.getId());
            } else {
                
                HttpMethods.getFriendService()
                        .addFriend(new AddFriendReq(item.getId()))
                        .compose(RxUtil.<FriendNotification>applyScheduler())
                        .subscribe(new HttpSubscriber<FriendNotification>() {
                            @Override
                            protected void onSuccess(FriendNotification response) {
                                ToastUtil.showShort("请求成功");
                            }

                            @Override
                            protected void onFailure(String errMsg, @Nullable FriendNotification response, int code) {
                                DialogUtil.showError(mContext, errMsg);
                            }
                        });
            }
        }

        public void onTempChat(Profile item) {
            Realm realm = Realm.getInstance(ChatDB2.INSTANCE.getConfiguration());
            realm.beginTransaction();
            realm.insertOrUpdate(item);
            realm.commitTransaction();
            realm.close();

            ChatActivity.openActivity(mContext, "user:" + item.getId());
        }
    }

    public static class Util {
        public static String getAge(Profile profile) {
            Period p = new Period(new DateTime(DateUtil.parse(DateUtil.DATE_PATTERN, profile.getBirthday())), DateTime.now());
            return String.valueOf(p.getYears());
        }

        public static String getGender(Profile profile) {
            if (profile.isGender()) {
                return "男";
            } else {
                return "女";
            }
        }

        public static String getBottomText(Boolean isFriend) {
            if (isFriend == null) {
                return null;
            }
            if (isFriend) {
                return "去聊天";
            } else {
                return "加为好友";
            }
        }

        public static int setTransformationMethod(boolean isPublic){
            if (isPublic) {
                return InputType.TYPE_CLASS_TEXT;
            }else{
                return InputType.TYPE_TEXT_VARIATION_PASSWORD|InputType.TYPE_CLASS_TEXT;
            }
        }

    }
}
